package com.probiz.estore.cart.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.common.model.cart.Shoppingcart;
import com.probiz.estore.common.model.cart.ShoppingcartItem;
import com.probiz.estore.webapp.util.RequestContext;
import com.probiz.estore.webapp.util.RequestUtil;
import com.probiz.estore.webapp.util.ResponseContext;

public class ShoppingCartUtil {
	private Logger logger = Logger.getLogger(ShoppingCartUtil.class);
	private final static ShoppingCartUtil shoppingCartUtil = new ShoppingCartUtil();
	public static final String	SHOPPINGCART_COOKIE		= "shoppingcartInCookie";

	public static synchronized ShoppingCartUtil  getInstance(){
		return shoppingCartUtil;
	}
	
	public Shoppingcart getCurrentUserShoppingcart() {
		HttpSession session = RequestContext.getCurrentHttpRequest().getSession();
		Shoppingcart shoppingcart = (Shoppingcart)session.getAttribute("shoppingcart");
		
		if (shoppingcart == null) {
			//get from cookie
			shoppingcart = new Shoppingcart();
			if (RequestContext.getCurrentUser() != null) {// 匿名用户浏览时customer可以为null
				shoppingcart.setOwner(RequestContext.getCurrentUser());
			}
			shoppingcart.setUuid(UUID.randomUUID().toString());
			shoppingcart.setIsUsedCoupon((short) 0);
			shoppingcart.setCreateTime(new Date(System.currentTimeMillis()));
			initializeShoppingcartByCookie(shoppingcart);
			session.setAttribute("shoppingcart", shoppingcart);
		}
		
		return shoppingcart;
	}
	
	public void clearCurrentUserShoppingcart() {
		HttpSession session = RequestContext.getCurrentHttpRequest().getSession();
		session.removeAttribute("shoppingcart");
	}
	
	
	//用cookie中的购物车数据初始购物车
	private void initializeShoppingcartByCookie(Shoppingcart shoppingcart) {
		Cookie cookie = RequestUtil.getCookie(RequestContext.getCurrentHttpRequest(), SHOPPINGCART_COOKIE);
		if (cookie != null) {
			String cookieValue = cookie.getValue();
			
			//使用base64进行解码
			Base64 base64 = new Base64();
			cookieValue = new String(base64.decode(cookieValue.getBytes()));
			  
			String[] itemStrings = cookieValue.split("@");
			try{
				if (itemStrings != null) {
					for (String itemString: itemStrings) {
						String[] itemArray = itemString.split("~");
						if (itemArray!= null && itemArray.length >= 2) {
							String productSkuCode = itemArray[0];
							try {
								//解码中文
								productSkuCode = java.net.URLDecoder.decode(productSkuCode, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								//DO NOTHING
							}
							String quanlity = itemArray[1];
							quanlity = quanlity.trim();
							if(StringUtils.isNotBlank(quanlity)){
								try {
									shoppingcart.addProductItem(productSkuCode, Integer.valueOf(quanlity));
								} catch (NumberFormatException e) {
									logger.error("初始cookie购物车失败 ShoppingCartUtil.java 81 行！",e);
									e.printStackTrace();
								}
							}
						}
					}
					
				}
			}catch(Exception e){
				//发生异常，则清空购物车
				e.printStackTrace();
				RequestUtil.setCookie(ResponseContext.getCurrentHttpResponse(), ShoppingCartUtil.SHOPPINGCART_COOKIE, "", RequestContext.getCurrentHttpRequest().getContextPath());
				ShoppingCartUtil.getInstance().clearCurrentUserShoppingcart();
			}
		}
	}
	
	//把购物车数据保存到cookie。格式是  skuCode1~数量1@skuCode2~数量2@skuCode3~数量3@skuCode4~数量4@ .....
	public void updateShoppingcartCookie(Shoppingcart shoppingcart, HttpServletResponse response) {
		StringBuilder sb = new StringBuilder();
		if (shoppingcart != null) {
			for (ShoppingcartItem shippingcartItem: shoppingcart.getProductItems()) {
				try {
					//对中文进行编码(cookie不允许含有中文)
					sb.append(java.net.URLEncoder.encode(shippingcartItem.getProductSku().getProductSkuCode(), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					sb.append(shippingcartItem.getProductSku().getProductSkuCode());
				}
				sb.append("~");
				sb.append(shippingcartItem.getQuantity());
				sb.append("@");
			}
		}
		
		//使用base64对字符串编码(cookie不允特殊字符)
		Base64 base64 = new Base64();
		String cookieValue = new String(base64.encode(sb.toString().getBytes()));

		RequestUtil.setCookie(response, SHOPPINGCART_COOKIE, cookieValue, RequestContext.getCurrentHttpRequest().getContextPath());
	}
	
}
